#!/usr/bin/env python3
"""
Update a WebExtension build manifest with info on a given build
"""
import argparse
import sys
import shutil
import json
import traceback
from distutils.version import LooseVersion

parser = argparse.ArgumentParser(
    description='Update a WebExtension build manifest with info on a given build',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)

parser.add_argument('-f', '--file', required=True, help="path to updates.json")
parser.add_argument('-c', '--channel', required=True, help='release channel')
parser.add_argument('-v', '--version', required=True, help='version number of XPI')
parser.add_argument('-s', '--sha', required=True, help="SHA256 of XPI")

args = parser.parse_args()

def main():
    try:
        file = args.file
        version = args.version
        channel = args.channel
        sha = args.sha
        
        # Read in existing file
        with open(file) as f:
            manifest = json.loads(f.read())
        
        updates = manifest['addons']['zotero@chnm.gmu.edu']['updates']
        
        if any(u['version'] == version for u in updates):
            sys.stderr.write(
                "Update with version '{0}' already exists in manifest\n"
                .format(version)
            )
            return 1
        
        url = ("https://download.zotero.org/connector/" +
               "firefox/{0}/Zotero_Connector-{1}.xpi".format(channel, version))
        min_version = "51.0"
        updates.append({
            "version": version,
            "update_link": url,
            "update_hash": "sha256:" + sha,
            "applications": {
                "gecko": {
                    "strict_min_version": min_version
                }
            }
        })
        updates = sorted(updates, key=lambda item: LooseVersion(item['version']))
        
        # Keep last 5 versions
        manifest['addons']['zotero@chnm.gmu.edu']['updates'] = updates[-5:]
        
        # Back up JSON file
        shutil.copy2(file, file + '.bak')
        
        # Write new file
        manifest = json.dumps(manifest, indent=2)
        with open(file, 'w') as f:
            f.write(manifest + "\n")
        
        print(manifest)
        
        return 0
    
    except Exception as err:
        sys.stderr.write("\n" + traceback.format_exc())
        return 1

if __name__ == '__main__':
    sys.exit(main())
